<script setup lang="ts" name="RetreatSet">
import { onMounted, reactive, ref, watch } from "vue";
import SelectShip from "@/components/SelectInfo/SelectShip.vue";
import SelectBill from "@/components/SelectInfo/SelectBill.vue";
import { type ConfigProviderThemeVars, showSuccessToast } from "vant";
import { showFailToast } from "vant";
import moment from "moment";
import {
  GetStorageByTransportBillId,
  GetTransportBillDetail,
  GetTransportShipDetail,
  SubmitOneStockTally,
  SubmitRetreatSet
} from "@/api/tally";
import { useBillInfo } from "@/store/bill-info";
import { useEditOstInfo } from "@/store/edit-ost-info";
import router from "@/router";
import { useDictInfo } from "@/store/dict";
import FloatHeader from "@/components/NavBar/FloatHeader.vue";
import SelectStorage from "@/components/SelectInfo/SelectStorage.vue";
import BigNumber from "bignumber.js";
import SelectRetreatType from "@/components/SelectInfo/SelectRetreatType.vue";
import { isNumeric } from "vant/es/utils";
import type { StorageData } from "@/utils/interface";

const dictStore = useDictInfo();
const timeSpaceList = ref([] as Array<any>);

const record = ref({} as any);
const isEdit = ref(false);
const isReuse = ref(false);
onMounted(() => {
  timeSpaceList.value = dictStore.getDictByCode("time_space");

  const editBillInfoStore = useEditOstInfo();
  record.value = editBillInfoStore.editOstInfo;

  if (record.value?.id) {
    console.log(record.value);

    isEdit.value = true;
    isReuse.value = record.value.isReuse;
    transportShip.id = record.value.transportShipId;
    transportShip.value = record.value.shipNameZh;
    getTransportShipDetail(transportShip.id);

    transportBill.id = record.value.transportBillId;
    transportBill.value = record.value.billNo;
    transportBill.isCheckWhs = true;
    getTransportBillDetail(transportBill.id);

    tallyDateAndTimeSpace.tallyDate = record.value.tallyDate;
    tallyDateAndTimeSpace.timeSpace = record.value.timeSpace;
    tallyDateAndTimeSpace.defaultDate = moment(record.value.tallyDate).toDate();
    tallyDateAndTimeSpace.outTimeSpace = record.value.outTimeSpace;

    retreatInfo.retreatStorageId = record.value.retreatStorageId;
    retreatInfo.storageInfo =
      record.value.storagePositionName +
      "-" +
      record.value.storageSpot +
      "-" +
      record.value.storagePackageTypeName;

    retreatInfo.retreatType = record.value.retreatType;
    retreatInfo.retreatName = record.value.retreatTypeName;
    retreatInfo.retreatPiece = record.value.retreatPiece;
    retreatInfo.retreatTon = record.value.retreatTon;
    retreatInfo.retreatType = record.value.retreatType;
    retreatInfo.leftPieceTon =
      record.value.storagePiece + "/" + record.value.storageTon;
    retreatInfo.retreatReason = record.value.retreatReason;
  }
});

const themeVars: ConfigProviderThemeVars = {
  cellLabelFontSize: "13px",
  fieldInputTextColor: "#7f7e7e",
  numberKeyboardZIndex: 1000,
  cellBorderColor: "#cccccc",
  borderWidth: "1.5px",
  cellHorizontalPadding: "0px",
  cellVerticalPadding: "10px",
  radioDotSize: "5px",
  radioLabelMargin: "3px",
  navBarTitleTextColor: "#ffffff",
  navBarIconColor: "#ffffff",
  fontBold: 0,
  popupBackground: "#f6f6f6"
};

const transportShip = reactive({
  id: "",
  value: "",
  showSelectShipPopup: false,
  showMoreShipInfo: [],
  showMore: false,
  detail: {} as any
});

function getTransportShipDetail(transportShipId: string) {
  GetTransportShipDetail({ transportShipId }).then((res: any) => {
    transportShip.detail = res.data;
  });
}

function beforeShowSelectShipPopup() {
  if (isEdit.value) {
    return;
  }
  transportShip.showSelectShipPopup = true;
}

const isSelectShipOpen = (value: boolean) => {
  transportShip.showSelectShipPopup = value;
};
const selectedShip = (value: any) => {
  transportBill.id = "";
  transportBill.value = "";
  transportBill.detail = "";
  transportShip.id = value.transportShipId;
  transportShip.value = value.shipNameZh;
  getTransportShipDetail(transportShip.id);
};

const transportBill = reactive({
  id: "",
  value: "",
  showSelectBillPopup: false,
  isCheckWhs: false,
  detail: {} as any
});
watch(
  () => transportBill.id,
  newValue => {
    transportBill.isCheckWhs = !newValue;
  },
  { immediate: true }
);

function beforeShowSelectBillPopup() {
  if (isEdit.value) {
    return;
  }
  if (!transportShip.id) {
    showFailToast("请先选择船");
    return;
  }
  transportBill.showSelectBillPopup = true;
}

const isSelectBillOpen = (value: boolean) => {
  transportBill.showSelectBillPopup = value;
};
const selectedBill = (value: any) => {
  transportBill.id = value.transportBillId;
  transportBill.value = value.billNo;

  getTransportBillDetail(transportBill.id);
};

function getTransportBillDetail(transportBillId: string) {
  GetTransportBillDetail({ transportBillId }).then((res: any) => {
    transportBill.detail = res.data;
    GetStorageByTransportBillId({ transportBillId }).then((store: any) => {
      transportBill.detail.storagePiece = store.data.piece;
      transportBill.detail.storageTon = store.data.ton;
      const billInfoStore = useBillInfo();
      billInfoStore.setBillInfo(transportBill.detail);
    });
  });
}

const tallyDateAndTimeSpace = reactive({
  showCalendar: false,
  defaultDate: new Date(),
  minDate: new Date(new Date().setDate(new Date().getDate() - 180)),
  maxDate: new Date(new Date().setDate(new Date().getDate() + 30)),
  tallyDate: moment(new Date()).format("YYYY-MM-DD"),
  timeSpace:
    new Date().getHours() >= 8 && new Date().getHours() <= 19 ? "DAY" : "NIGHT",
  outTimeSpace: ""
});

function onCalendarConfirm(dates: any) {
  tallyDateAndTimeSpace.tallyDate = moment(dates).format("YYYY-MM-DD");
  tallyDateAndTimeSpace.showCalendar = false;
}

const retreatInfo = reactive({
  storageInfo: "",
  leftPieceTon: "",
  retreatPiece: "",
  retreatTon: "",
  retreatStorageId: "",
  retreatType: "",
  retreatName: "",
  retreatReason: ""
});

const validator = (val: any) => isNumeric(val);
const showSelectStoragePopup = ref(false);

const isSelectStorageOpen = (value: boolean) => {
  showSelectStoragePopup.value = value;
};
const selectedStorage = (res: StorageData) => {
  if (res.id) {
    retreatInfo.storageInfo =
      res.positionName + "-" + res.spot + "-" + res.packageTypeName;
    retreatInfo.retreatStorageId = res.id;
    retreatInfo.retreatTon = res.ton;
    retreatInfo.retreatPiece = String(res.piece);
    retreatInfo.leftPieceTon = res.piece + "/" + res.ton;
  }
};

const showSelectRetreatTypePopup = ref(false);

const isSelectRetreatTypeOpen = (value: boolean) => {
  showSelectRetreatTypePopup.value = value;
};
const selectedRetreatType = (res: any) => {
  retreatInfo.retreatType = res.dictKey;
  retreatInfo.retreatName = res.dictValue;
};

// 填写件数算吨数
const perTon = ref(0);

function setTon() {
  setPerTon();
  if (retreatInfo.retreatPiece && perTon.value) {
    retreatInfo.retreatTon = new BigNumber(retreatInfo.retreatPiece as string)
      .times(perTon.value)
      .toString();
  }
}

function setPerTon() {
  if (transportBill.id && transportBill.detail.piece !== 0) {
    const ton = new BigNumber(transportBill.detail.ton);
    const piece = new BigNumber(transportBill.detail.piece);
    perTon.value = ton.div(piece).toNumber();
  }
}

const isContinue = ref(false);
const isLoading = ref(false);
const onSubmit = (value: any) => {
  const postData = {
    id: record.value?.id,
    transportShipId: transportShip.id,
    transportBillId: transportBill.id,
    tallyDate: tallyDateAndTimeSpace.tallyDate,
    timeSpace: tallyDateAndTimeSpace.timeSpace,
    retreatPiece: retreatInfo.retreatPiece,
    retreatTon: retreatInfo.retreatTon,
    retreatStorageId: retreatInfo.retreatStorageId,
    retreatType: retreatInfo.retreatType,
    retreatReason: retreatInfo.retreatReason
  };

  if (isReuse.value) {
    postData.id = "";
  }

  isLoading.value = true;
  SubmitRetreatSet(postData)
    .then((res: any) => {
      console.log(res);
      if (res.success) {
        if (!isContinue.value) {
          const editInfo = useEditOstInfo();
          editInfo.removeEditOstInfo();
          showSuccessToast("提交成功");
          setTimeout(() => {
            router.back();
          }, 500);
          return;
        }
        record.value.id = "";
        selectedBill({
          transportBillId: transportBill.id,
          billNo: transportBill.value
        });
        showSuccessToast("提交成功");
      } else {
        showFailToast("提交失败");
      }
      isLoading.value = false;
    })
    .catch(() => {
      isLoading.value = false;
    });
};
const onFailed = (value: any) => {
  showFailToast("请检查表单");
};

function goBack(): void {
  const editInfo = useEditOstInfo();
  const billInfo = useBillInfo();
  editInfo.removeEditOstInfo();
  billInfo.removeBillInfo();
  router.back();
}
</script>

<template>
  <div
    class="container flex flex-col bg-gray-100 bg-no-repeat bg-contain bg-scroll back-image"
    ref="self"
  >
    <van-config-provider :theme-vars="themeVars">
      <FloatHeader :title="'退关设置'"></FloatHeader>
      <van-nav-bar
        class="mt-[60px] text-white"
        style="background: transparent"
        :border="false"
        title="退关设置"
        @click-left="goBack"
        left-arrow
      />
      <div class="flex flex-col h-auto w-[95%] mx-auto">
        <div class="flex-col flex w-full h-auto mb-[20px]">
          <div class="flex justify-center">
            <div class="w-full flex flex-col">
              <van-form @submit="onSubmit" @failed="onFailed">
                <!-- 船名舱单  -->
                <div
                  id="shipBillInfo"
                  class="w-full flex flex-col bg-white py-[10px] px-[15px] mt-1 rounded-lg"
                >
                  <div class="w h-[40px] flex justify-between">
                    <div class="flex h w items-center font-bold">
                      船舶舱单信息
                    </div>
                    <div class="flex h w items-center">
                      <a
                        class="text-xs"
                        style="color: #4486fa"
                        @click="
                          transportShip.showMore = !transportShip.showMore
                        "
                      >
                        查看船名单号详情
                        <van-icon name="arrow" />
                      </a>
                    </div>
                  </div>
                  <van-cell-group :border="false">
                    <!-- 选择船名 -->
                    <van-field
                      :border="true"
                      :disabled="isEdit"
                      is-link
                      readonly
                      v-model="transportShip.value"
                      name="shipName"
                      placeholder="请选择船名"
                      @click="beforeShowSelectShipPopup"
                      :rules="[{ required: true, message: '请选择船名' }]"
                    >
                      <template #label>
                        船名<span class="xing">*</span>
                      </template>
                    </van-field>
                    <van-popup
                      v-model:show="transportShip.showSelectShipPopup"
                      position="bottom"
                      round
                      duration="0"
                      :style="{ height: 'auto' }"
                    >
                      <SelectShip
                        @isOpen="isSelectShipOpen"
                        @selectedShip="selectedShip"
                      ></SelectShip>
                    </van-popup>
                    <!-- 选择单号 -->
                    <van-field
                      :border="false"
                      :disabled="isEdit"
                      is-link
                      readonly
                      v-model="transportBill.value"
                      name="billNo"
                      placeholder="请选择单号"
                      @click="beforeShowSelectBillPopup"
                      :rules="[{ required: true, message: '请选择单号' }]"
                    >
                      <template #label>
                        单号<span class="xing">*</span>
                      </template>
                    </van-field>
                    <van-popup
                      v-model:show="transportBill.showSelectBillPopup"
                      position="bottom"
                      round
                      duration="0"
                      :style="{ height: 'auto' }"
                    >
                      <SelectBill
                        :shipId="transportShip.id"
                        @isOpen="isSelectBillOpen"
                        @selectedBill="selectedBill"
                      ></SelectBill>
                    </van-popup>
                    <!-- 船单号信息 -->
                    <Transition name="fade">
                      <div
                        class="w-[95%] mx-auto h-auto mt-[5px]"
                        style="background: #f2f6ff"
                        v-if="transportShip.showMore"
                      >
                        <div class="flex flex-col w-full h-auto gap-2 p-[12px]">
                          <div class="flex w-full">
                            <div class="w-1/3 flex text-sm text-gray-400">
                              船名
                            </div>
                            <div class="flex flex-1 text-sm ml-[10px]">
                              {{ transportShip.detail?.shipNameZh }}
                            </div>
                          </div>
                          <div class="flex w-full">
                            <div class="w-1/3 flex text-sm text-gray-400">
                              进口航次
                            </div>
                            <div class="flex flex-1 text-sm ml-[10px]">
                              {{ transportShip.detail?.impVoyage }}
                            </div>
                          </div>
                          <div class="flex w-full">
                            <div class="w-1/3 flex text-sm text-gray-400">
                              出口航次
                            </div>
                            <div class="flex flex-1 text-sm ml-[10px]">
                              {{ transportShip.detail?.expVoyage }}
                            </div>
                          </div>
                          <div class="flex w-full">
                            <div class="w-1/3 flex text-sm text-gray-400">
                              预报状态
                            </div>
                            <div class="flex flex-1 text-sm ml-[10px]">
                              {{ transportShip.detail?.forecastStatusName }}
                            </div>
                          </div>
                          <div class="flex w-full">
                            <div class="w-1/3 flex text-sm text-gray-400">
                              单号
                            </div>
                            <div class="flex flex-1 text-sm ml-[10px]">
                              {{ transportBill.detail?.billNo }}
                            </div>
                          </div>
                          <div class="flex w-full">
                            <div class="w-1/3 flex text-sm text-gray-400">
                              进出口
                            </div>
                            <div class="flex flex-1 text-sm ml-[10px]">
                              {{ transportBill.detail?.ieName }}
                            </div>
                          </div>
                          <div class="flex w-full">
                            <div class="w-1/3 flex text-sm text-gray-400">
                              货名
                            </div>
                            <div class="flex flex-1 text-sm ml-[10px]">
                              {{ transportBill.detail?.cargoTypeName }}
                            </div>
                          </div>
                          <div class="flex w-full">
                            <div class="w-1/3 flex text-sm text-gray-400">
                              计划/库存件数
                            </div>
                            <div class="flex flex-1 text-sm ml-[10px]">
                              {{ transportBill.detail?.piece }} /
                              {{ transportBill.detail?.storagePiece }}
                            </div>
                          </div>
                          <div class="flex w-full">
                            <div class="w-1/3 flex text-sm text-gray-400">
                              计划/库存吨数
                            </div>
                            <div class="flex flex-1 text-sm ml-[10px]">
                              {{ transportBill.detail?.ton }} /
                              {{ transportBill.detail?.storageTon }}
                            </div>
                          </div>
                        </div>
                      </div>
                    </Transition>
                  </van-cell-group>
                </div>
                <!-- 日期班次  -->
                <div
                  id="tallyDateShift"
                  class="w-full flex flex-col bg-white py-[10px] px-[15px] rounded-lg mt-3"
                >
                  <div class="w h-[40px] flex justify-between">
                    <div class="flex h w items-center font-bold">日期班次</div>
                  </div>
                  <van-cell-group :border="false">
                    <van-field
                      is-link
                      readonly
                      v-model="tallyDateAndTimeSpace.tallyDate"
                      name="tallyDate"
                      placeholder="请选择工班日期"
                      @click="tallyDateAndTimeSpace.showCalendar = true"
                      :rules="[{ required: true, message: '请选择工班日期' }]"
                    >
                      <template #label>
                        日期<span class="xing">*</span>
                      </template>
                    </van-field>
                    <van-calendar
                      :min-date="tallyDateAndTimeSpace.minDate"
                      :max-date="tallyDateAndTimeSpace.maxDate"
                      :default-date="tallyDateAndTimeSpace.defaultDate"
                      duration="0"
                      v-model:show="tallyDateAndTimeSpace.showCalendar"
                      :show-confirm="false"
                      @confirm="onCalendarConfirm"
                    />

                    <van-field
                      :border="false"
                      name="timeSpace"
                      :rules="[{ required: true, message: '请选择班次' }]"
                    >
                      <template #label>
                        班次<span class="xing">*</span>
                      </template>
                      <template #input>
                        <van-radio-group
                          shape="dot"
                          v-model="tallyDateAndTimeSpace.timeSpace"
                          direction="horizontal"
                        >
                          <van-radio
                            icon-size="18px"
                            :key="item?.dictKey"
                            v-for="item in timeSpaceList"
                            :name="item?.dictKey"
                            >{{ item?.dictValue }}
                          </van-radio>
                        </van-radio-group>
                      </template>
                    </van-field>
                  </van-cell-group>
                </div>

                <div
                  class="w-full flex flex-col bg-white py-[10px] px-[15px] rounded-lg mt-3"
                >
                  <div class="w h-[40px] flex justify-between">
                    <div class="flex h w items-center font-bold">退关量</div>
                  </div>
                  <van-cell-group :border="false">
                    <van-field
                      readonly
                      name="position"
                      label="货垛"
                      placeholder="请选择货垛"
                      is-link
                      v-model="retreatInfo.storageInfo"
                      @click="showSelectStoragePopup = true"
                      :rules="[{ required: true, message: '请选择货垛' }]"
                    >
                      <template #label>
                        货垛<span class="xing">*</span>
                      </template>
                    </van-field>
                    <van-popup
                      v-model:show="showSelectStoragePopup"
                      position="bottom"
                      round
                      duration="0"
                      class="bg-slate-400 h-[calc(100vh-100px)]"
                    >
                      <SelectStorage
                        :transportBillId="transportBill.id"
                        :storageId="retreatInfo.retreatStorageId"
                        @isOpen="isSelectStorageOpen"
                        @selectedStorage="selectedStorage"
                      ></SelectStorage>
                    </van-popup>
                    <van-field
                      readonly
                      disabled
                      v-model="retreatInfo.leftPieceTon"
                      name="leftPieceTon"
                      label="货垛剩余"
                    />
                    <van-field
                      readonly
                      disabled
                      v-model="perTon"
                      name="perTon"
                      label="舱单单吨"
                    />
                    <van-field
                      name="piece"
                      v-model="retreatInfo.retreatPiece"
                      label="理货件数"
                      placeholder="请输入件数"
                      :rules="[{ validator, message: '请输入件数' }]"
                    >
                      <template #label>
                        退关件数<span class="xing">*</span>
                      </template>
                    </van-field>
                    <van-field
                      name="ton"
                      v-model="retreatInfo.retreatTon"
                      @focus="setTon"
                      :border="false"
                      label="理货吨数"
                      placeholder="请输入吨数"
                      :rules="[{ validator, message: '请输入吨数' }]"
                    >
                      <template #label>
                        退关吨数<span class="xing">*</span>
                      </template>
                    </van-field>
                  </van-cell-group>
                </div>

                <div
                  class="w-full flex flex-col bg-white py-[10px] px-[15px] rounded-lg mt-3"
                >
                  <div class="w h-[40px] flex justify-between">
                    <div class="flex h w items-center font-bold">退关原因</div>
                  </div>
                  <van-cell-group :border="false">
                    <van-field
                      readonly
                      name="retreatType"
                      label="退关类型"
                      placeholder="请选择退关类型"
                      is-link
                      v-model="retreatInfo.retreatName"
                      @click="showSelectRetreatTypePopup = true"
                      :rules="[{ required: true, message: '请选择退关原因' }]"
                    >
                      <template #label>
                        退关类型<span class="xing">*</span>
                      </template>
                    </van-field>
                    <van-popup
                      v-model:show="showSelectRetreatTypePopup"
                      position="bottom"
                      round
                      duration="0"
                      :style="{ height: 'auto' }"
                      class="bg-slate-400"
                    >
                      <SelectRetreatType
                        :retreatType="retreatInfo.retreatType"
                        @isOpen="isSelectRetreatTypeOpen"
                        @selectRetreatType="selectedRetreatType"
                      ></SelectRetreatType>
                    </van-popup>
                    <van-field
                      name="ton"
                      v-model="retreatInfo.retreatReason"
                      :border="false"
                      label="退关原因"
                      placeholder="请输入退关原因"
                    >
                      <template #label> 退关原因 </template>
                    </van-field>
                  </van-cell-group>
                </div>

                <!-- 返回顶部  -->
                <van-back-top right="5vw" bottom="15vh" />
                <!-- 按钮组  -->
                <div style="margin: 16px">
                  <div class="flex w-full gap-2" v-if="!isLoading">
                    <van-button
                      class="flex flex-1"
                      block
                      color="#e6edff"
                      style="color: #4e6eb3"
                      native-type="submit"
                      @click="isContinue = false"
                    >
                      保存并提交
                    </van-button>
                    <van-button
                      class="flex flex-1"
                      block
                      color="#175eff"
                      native-type="submit"
                      @click="isContinue = true"
                    >
                      保存并继续
                    </van-button>
                  </div>
                  <div class="flex w-full gap-2" v-if="isLoading">
                    <van-button
                      class="flex flex-1"
                      block
                      disabled
                      loading
                      color="#e6edff"
                      style="color: #4e6eb3"
                      native-type="submit"
                      @click="isContinue = false"
                    >
                      保存并提交
                    </van-button>
                    <van-button
                      class="flex flex-1"
                      block
                      disabled
                      loading
                      color="#175eff"
                      native-type="submit"
                      @click="isContinue = true"
                    >
                      保存并继续
                    </van-button>
                  </div>
                </div>
              </van-form>
            </div>
          </div>
        </div>
      </div>
    </van-config-provider>
  </div>
</template>
<style scoped>
.header {
  background: linear-gradient(144deg, rgba(64, 169, 255, 1) 6%, #f7f8fa 6%);
}

.back-image {
  background-image: url("../../assets/back.png");
}
</style>
